package com.bit.demo16;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class EchoClient {
    private DatagramSocket socket=null;
    private String serverIP;
    private int serverPort;
    public EchoClient(String serverIP,int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        socket=new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while(true){
            // 1. 从控制台读取用户输入的内容
            System.out.println("请输入发送到服务器的内容");
            String request=scanner.next();
            // 2. 构造成 UDP 请求, 并发送. 不光要填内容, 还要填服务器的地址和端口.
            DatagramPacket reqPacket=new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            socket.send(reqPacket);
            // 3. 读取服务器的响应.
            DatagramPacket respPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(respPacket);
            String response=new String(respPacket.getData(),0,respPacket.getLength());
            // 4. 把响应显示到控制台.
            System.out.println("收到服务器的响应:"+response);
        }
    }

    public static void main(String[] args) throws IOException {
        EchoClient client = new EchoClient("127.0.0.1",9090);
        client.start();
    }
}